import React, { useState, ChangeEventHandler, ChangeEvent } from 'react';
import { Button, Tabs, Space, Select, message } from 'antd';
import { Resizable } from 'react-resizable';
import { DownOutlined, UpOutlined, ClearOutlined, UploadOutlined } from '@ant-design/icons'
import { useDispatch, useSelector } from "react-redux";
import ScreenshotList from '@/components/ScreenshotList';
import CSVList from '@/components/CSVList'
import VisualList from '@/components/VisualList'
import LogList from '@/components/LogList'
import VariableList from '@/components/VariableList'
import { clearLogs, clearScreenshots, updateConfig } from '@/actions'
import { State } from '@/reducers';
import { getStorageManager } from '@/file_storage'
import { sanitizeFileName } from '@/common/utils';
import { listCSV } from '@/actions'
import './index.less';

interface HandleProps {
    handleAxis: string;
    [key: string]: any;
}

const ResizeHandle = React.forwardRef<HTMLDivElement, HandleProps>((props, ref) => {
    const { handleAxis, ...restProps } = props;
    return <div ref={ref} className={`panel-footer-resize-handle handle-${handleAxis}`} {...restProps} />;
});

export default function PanelFooter() {
    const dispatch = useDispatch()
    const [height, setHeight] = useState(160);
    const [isExpanded, setIsExpanded] = useState(true);
    const [activeKey, setActiveKey] = useState('logs')
    const logFilter = useSelector((state: State) => state.config.logFilter)


    // 上传CSV
    const onFileChange: ChangeEventHandler<HTMLInputElement> = (e: ChangeEvent<HTMLInputElement>) => {
        const csvStorage = getStorageManager().getCSVStorage()
        const files = [].slice.call(e.target.files)
        if (!files || !files.length) return

        const read = (file: File) => {
            return new Promise((resolve, reject) => {
                const reader = new FileReader()
                reader.onload = (readerEvent) => {
                    const text = readerEvent.target!.result
                    resolve({
                        text,
                        fileName: file.name
                    })
                }
                reader.readAsText(file)
            })
        }

        Promise.all(files.map(read))
            .then((list: any[]) => {
                const ps = list.map(fileItem => csvStorage.write(sanitizeFileName(fileItem.fileName), new Blob([fileItem.text])))
                return Promise.all(ps).then(() => dispatch(listCSV() as any))
                    .then(() => {
                        message.info(`${list.length} csv files imported`)
                    })
            })
            .catch(e => {

            })
    }

    return (
        <Resizable
            width={Infinity}
            height={isExpanded ? height : 32}
            onResize={(e, { size }) => {
                setHeight(Math.max(32, size.height));
            }}
            handle={isExpanded ? <ResizeHandle handleAxis="y" /> : <></>}
            axis="y"
            minConstraints={[Infinity, 50]}
            maxConstraints={[Infinity, window.innerHeight * 0.8]}
            draggableOpts={{
                enableUserSelectHack: false,
                grid: [1, 1]
            }}
            handleSize={[0, 10]}
            resizeHandles={['n']}
        >
            <div className="panel-footer" style={{ height: isExpanded ? height : 32 }}>
                <Tabs
                    type="card"
                    size="small"
                    tabPosition="top"
                    activeKey={activeKey}
                    onChange={setActiveKey}
                    items={[
                        {
                            key: 'logs',
                            label: '运行日志',
                            children: <LogList />
                        },
                        {
                            key: 'variables',
                            label: '运行变量',
                            children: <VariableList />
                        },
                        {
                            key: 'screenshots',
                            label: '截图列表',
                            children: <ScreenshotList />
                        },
                        {
                            key: 'csv',
                            label: 'CSV列表',
                            children: <CSVList />
                        },
                        {
                            key: 'visual',
                            label: '图像库',
                            children: <VisualList />
                        }
                    ]}
                    tabBarExtraContent={
                        <Space>
                            {
                                activeKey === 'logs' && [
                                    <Select
                                        key="log-filter"
                                        value={logFilter}
                                        onChange={(value) => {
                                            dispatch(updateConfig({ logFilter: value }))
                                        }}
                                        style={{ width: '60px' }}
                                        popupMatchSelectWidth={false}
                                        size="small"
                                    >
                                        <Select.Option value='All'>All</Select.Option>
                                        <Select.Option value='Echo'>Echo</Select.Option>
                                        <Select.Option value='Echo_And_Status'>Echo &amp; Status</Select.Option>
                                        <Select.Option value='Error'>Error &amp; Reports</Select.Option>
                                        <Select.Option value='None'>No log</Select.Option>
                                    </Select>,
                                    <Button
                                        key="log-clear"
                                        size="small"
                                        icon={<ClearOutlined />}
                                        onClick={() => {
                                            dispatch(clearLogs());
                                        }} />
                                ]
                            }
                            {
                                activeKey === 'screenshots' && <Button
                                    size="small"
                                    onClick={() => {
                                        dispatch(clearScreenshots());
                                    }}
                                    icon={<ClearOutlined />}
                                />
                            }
                            {
                                activeKey === 'csv' && <Button
                                    size="small"
                                    className="load-csv-button"
                                    icon={<UploadOutlined />}
                                >
                                    <input
                                        multiple
                                        type="file"
                                        accept=".csv"
                                        id="select_csv_files"
                                        onChange={onFileChange}
                                        style={{ display: 'none' }}

                                    />
                                </Button>
                            }
                            <Button
                                type='text'
                                size="small"
                                onClick={() => {
                                    setIsExpanded(isExpanded => !isExpanded)
                                }}
                                icon={isExpanded ? <DownOutlined /> : <UpOutlined />} />
                        </Space>
                    }
                    className='panel-footer-tabs'
                />
            </div>
        </Resizable>
    );
}
